﻿using System.Data;

namespace Viyi.Util.Data.Converter
{
    /// <summary>
    /// 用于将指定列的数据，按指定的字符串格式，转换成字符串。
    /// 如：对日期字段按{0:yyyy-MM-dd}格式进行转换可以日期输出为2012-12-21这样的格式
    /// </summary>
    public class FormatColumnConverter : DataTableColumnConverter
    {
        string formatPattern;

        /// <summary>
        /// 使用一个格式来构造<c>FormatClumnConverter</c>。
        /// </summary>
        /// <param name="formatPattern">格式，参阅<see cref="string.Format(string, object[])"/></param>
        public FormatColumnConverter(string formatPattern)
        {
            if (formatPattern != null
                && formatPattern.IndexOf("{0", System.StringComparison.Ordinal) >= 0)
            {
                this.formatPattern = formatPattern;
            }
            else
            {
                this.formatPattern = "{0:" + formatPattern + "}";
            }
        }

        /// <summary>
        /// 根据源列创建一个新列用于保存转换结果。新列数据类型为<c>string</c>
        /// </summary>
        /// <param name="originColumn">源列</param>
        /// <param name="newColumnName">新列名</param>
        /// <returns>创建的新列</returns>
        protected override DataColumn GenerateColumn(DataColumn originColumn, string newColumnName)
        {
            DataColumn column = base.GenerateColumn(originColumn, newColumnName);
            column.DataType = typeof(string);
            return column;
        }

        /// <summary>
        /// 将源列数据，按构造时指定的格式，产生新列的<c>string</c>类型数据。
        /// </summary>
        /// <param name="row">数据行</param>
        /// <param name="columnIndex">源列索引</param>
        /// <param name="newColumnIndex">新列索引</param>
        protected override void Convert(DataRow row, int columnIndex, int newColumnIndex)
        {
            row[newColumnIndex] = string.Format(formatPattern, row.ObjectValue(columnIndex));
        }
    }
}
